//
//  GloableEngineService.m
//  iphoneTravelTour
//
//  Created by chen jiedan on 13-1-8.
//  Copyright (c) 2013年 Baidu. All rights reserved.
//

#import "GloableEngineService.h"
#import "Reachability.h"
#import "BMKMapManager.h"
#import "BMKSearch.h"
#import "AppDelegate.h"
#import "RCSearchAllCityTagDataModel.h"
#import "AppDelegate.h"
#import "RCSearchMoreTagsVC.h"
#import "TravelException.h"
#import "NSString+NSString_Ex_.h"
#import "RCLoginPageVC.h"


#define kLatitude               @"userLatitude"
#define kLongitude              @"userLongitude"


//#import "CityApp.h"
//#import "Request.h"
//#import "Utility.h"

SYNTHESIZE_SINGLETON_FOR_CLASS_PROTOTYPE(GloableEngineService);
@implementation GloableEngineService{
    NCLocationController *_locationController;
}
SYNTHESIZE_SINGLETON_FOR_CLASS(GloableEngineService);

@synthesize userLocation = _userLocation;
@synthesize selectedCityName = _selectedCityName;
@synthesize selectedCityID  = _selectedCityID;
@synthesize userCityStreetName = _userCityStreetName;
@synthesize userSelectStreetName = _userSelectStreetName;;
@synthesize userCityName;
@synthesize GPSEnabled;
@synthesize networkOK;
@synthesize netWorkStatus = _netWorkStatus;
@synthesize mapReady      = _mapReady;
@synthesize locationInfo = _locationInfo;
@synthesize hasLogin     = _hasLogin;
@synthesize nickName     = _nickName;
@synthesize bduss        = _bduss;
@synthesize userEmailName = _userEmailName;
@synthesize shopBduss = _shopBduss;
@synthesize shopID    = _shopID;
@synthesize shopName  = _shopName;
@synthesize search    = _search;
@synthesize delegate = _delegate;

- (id) initWithDefaultLocController
{
    self = [super init];
    if (self) {
        _locationController = [[NCLocationController alloc] init];
        _locationController.delegate = self;
        
        GPSEnabled = [CLLocationManager locationServicesEnabled];
        
        self.networkOK = NO;

        Reachability *networkReachable = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reachabilityChanged:)
                                                     name:kReachabilityChangedNotification
                                                   object:nil];

        [networkReachable startNotifier];
        
        NSString *latitude = [[NSUserDefaults standardUserDefaults]objectForKey:kLatitude];
        NSString *longitude = [[NSUserDefaults standardUserDefaults]objectForKey:kLongitude];
        if (latitude != nil && longitude != nil) {
            CLLocationDegrees lat = [latitude doubleValue];
            CLLocationDegrees lon = [longitude doubleValue];
            self.userLocation = CLLocationCoordinate2DMake(lat, lon);
            self.locationInfo = [[[CLLocation alloc]initWithLatitude:lat longitude:lon]autorelease];
        }
        
        BMKMapManager *_mapManager = [[BMKMapManager alloc]init];
        // 如果要关注网络及授权验证事件，请设定generalDelegate参数
        BOOL ret = [_mapManager start:@"1a661d86e4bedfc17264801f9978917b" generalDelegate:nil];
        if (!ret) {
            KFLog(@"manager start failed!");
        }
        
        _search = [[BMKSearch alloc]init];
        _search.delegate = self;
    }
    return self;
}


/*
 *更新用户当前地理位置信息
 **/
- (void) updataUserLocation
{
    [_locationController startUpdatingLocation];
}

- (void)locationUpdate:(CLLocation *)location
{
    NSLog(@"Latitude: %f", location.coordinate.latitude);
	NSLog(@"Longitude: %f", location.coordinate.longitude);
	NSLog(@"HorizontalAccuracy: %f", location.horizontalAccuracy);
	NSLog(@"VerticalAccuracy: %f", location.verticalAccuracy);
    #ifdef SimulateLocalCity
    
//    "CityName":"厦门市",
//    "Location":{"lat":"24.495019","lng":"118.135506"},
    CLLocationCoordinate2D newLoction;
    newLoction.latitude = 24.495019;
    newLoction.longitude = 118.135506;
    self.userLocation = newLoction;
    self.GPSEnabled = YES;
    #else
    self.locationInfo = location;
    self.userLocation = location.coordinate;
    self.GPSEnabled = YES;
    #endif
    
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%lf",self.userLocation.latitude] forKey:kLatitude];
    
    [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%lf",self.userLocation.longitude] forKey:kLongitude];
    
    [RCAppDelegate updateTheLocationInfo];
    
    if (_search == nil) {
        _search = [[BMKSearch alloc]init];
        _search.delegate = self;
        //发起反地理编码
    }

    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){location.coordinate.latitude, location.coordinate.longitude};
    pt = BMKCoorDictionaryDecode(BMKBaiduCoorForWgs84(pt));
    
    [_search reverseGeocode:pt];
    
}


- (void)locationError:(NSError *)error
{
//    self.userLocation
    self.GPSEnabled = NO;

}


- (void)onGetAddrResult:(BMKAddrInfo*)result errorCode:(int)error
{
    if (_delegate && [_delegate respondsToSelector:@selector(getPointAddress:errorCode:)]) {
        [_delegate getPointAddress:result errorCode:error];
        return;
    }
    NSString *city = [result.addressComponent city];
    NSString *streetName = [result.addressComponent streetName];
    NSLog(@"city NAME %@",city);
	// 在此处添加您对反地理编码结果的处理
    if (city != nil                 &&
        ![city isEqualToString:@""]) {
        NSRange range = [city rangeOfString:@"市"];
        if (range.location != NSNotFound) {
            city = [city stringByReplacingOccurrencesOfString:@"市" withString:@""];
        }
        self.userCityName = city;
        self.userCityStreetName = streetName;
        NSMutableDictionary *cityNameInfo = [[NSMutableDictionary alloc] init];
       
        //post notification
        [cityNameInfo setObject:self.userCityName forKey:@"CityName"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CityNameChanged"
                                                            object:cityNameInfo];
        [cityNameInfo release];
    }
    
}


- (void) setUserLocation:(CLLocationCoordinate2D)userLocation
{
    _userLocation = userLocation;
      //查找此单一目的地在地图上标识为哪个城市
//    BMKSearch *search = [[BMapViewService sharedInstance] searchInstance];
//    search.delegate = self;
//    [search reverseGeocode:_userLocation];
    //    NSLog(@"%f %f",_cityLocation.latitude, _cityLocation.longitude);
}



//#pragma mark 获取查询结果:用户当前所处位置
//- (void)onGetAddrResult:(BMKAddrInfo*)result errorCode:(int)error
//{
//    if (error == BMKErrorOk) {
//        if (result.addressComponent.city != nil) {
//            self.userCityName = [[[NSString alloc] initWithString:result.addressComponent.city] autorelease];
//        }
//    }else{
//        self.userCityName = nil;
//    }
//}

//- (BOOL) userIsInTourCity
//{
//    NSString *userCity = [[GloableEngineService sharedInstance] userCityName];
////#warning 这个地方需要在导游首页数据中 增加字段 哈尔滨市
//    NSString *tourCity = [[GloableEngineService sharedInstance] cityName];
////    tourCity = @"哈尔滨市";
//    BOOL sameCity = [userCity isEqualToString:tourCity];
//    if (sameCity) {
//        NSLog(@"在同一个城市里");
//        return YES;
//    }else{
//        NSLog(@"不在同个城市里");
//        return NO;
//    }
//}


#pragma mark 网络状况发生改变
- (void)reachabilityChanged:(NSNotification *)note
{
	Reachability* currentReach = [note object];
//    NSParameterAssert([currentReach isKindOfClass:Reachability.class]);
    NetworkStatus status = [currentReach currentReachabilityStatus];
    _netWorkStatus = status;
    if (status != NotReachable){// Network is okay.
        self.networkOK = YES;
        
      
        
        
	}else{
        self.networkOK = NO;
	}
}



#pragma
#pragma mark Tabbar 消息提示
/*
 * if message is nil value, the tabbar badge will be clear
 */
-(void) setTabbarIndex:(NSInteger)index withMessage:(NSString*)message
{

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (message != nil || ![message isEqualToString:@""]) {
        [userDefaults setObject:@"YES" forKey:@"TabbarNeedNotice"];
    }else{
        [userDefaults setObject:@"NO" forKey:@"TabbarNeedNotice"];
    }
    [userDefaults synchronize];
    
//    [TTAppDelegate.tabbarVC.tabBarView setBadgeValue:message forIndex:index];
    
}

#define kAccountBDUSS           @"account_bduss"
#define kAccountShopBDUSS       @"account_shopBduss"
#define kAccountShopID          @"account_shopID"
#define kAccountShopName          @"account_shopName"

#define kAccountName            @"account_nickname"
#define kAccountUserName        @"account_userEmailName"

#define kSelectID               @"selectid"
#define kSelectName             @"selectname"
#define kShopNameFromLogin      @"kShopNameFromLogin"

- (void) setUpLoginInfo
{
    NSString *bduss =  [[NSUserDefaults standardUserDefaults] objectForKey:kAccountBDUSS];
    NSString *nickName = [[NSUserDefaults standardUserDefaults] objectForKey:kAccountName];
    NSString *emailName = [[NSUserDefaults standardUserDefaults] objectForKey:kAccountUserName];
    
    if (bduss != nil && nickName != nil) {
        self.bduss = bduss;
        self.nickName = nickName;
        self.userEmailName = emailName;
        self.hasLogin = YES;
    }
    
    //商户宝相关信息
#ifdef ServerVersion
    NSString *shopID =  [[NSUserDefaults standardUserDefaults] objectForKey:kAccountShopID];
    NSString *shopName =  [[NSUserDefaults standardUserDefaults] objectForKey:kAccountShopName];
    NSString *shopBduss =  [[NSUserDefaults standardUserDefaults] objectForKey:kAccountShopBDUSS];
    NSString *cityID =  [[NSUserDefaults standardUserDefaults] objectForKey:kSelectID];
    NSString *cityName =  [[NSUserDefaults standardUserDefaults] objectForKey:kShopNameFromLogin];

    if (shopBduss != nil) {
        self.shopBduss = shopBduss;
        self.shopID = shopID;
        self.shopName = shopName;
        self.userCityName = cityName;
        self.selectedCityID = cityID;
        self.selectedCityName = cityName;
        self.hasLogin = YES;
    }else{
        self.hasLogin = NO;
    }

    
#endif

    
}

- (void) saveUserLoginInfo:(RCLoginDataModel *)loginInfo
{
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.bduss forKey:kAccountBDUSS];
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.nickName forKey:kAccountName];

    [[NSUserDefaults standardUserDefaults]synchronize];
    
    self.bduss = loginInfo.bduss;
    self.nickName = loginInfo.nickName;
    self.hasLogin = YES;
}


- (void) saveServerUserLoginInfo:(RCServerLoginDataModel *)loginInfo
{
    if (![NSString stringIsNullOrEmpty:loginInfo.memberbduss]) {
        [[NSUserDefaults standardUserDefaults] setObject:loginInfo.memberbduss forKey:kAccountBDUSS];
    }
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.username forKey:kAccountName];
//    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.cityid forKey:KAccountCityID];
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.shopbduss forKey:kAccountShopBDUSS];
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.shopid forKey:kAccountShopID];
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.shopname forKey:kAccountShopName];

    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.cityname forKey:kShopNameFromLogin];
    [[NSUserDefaults standardUserDefaults] setObject:loginInfo.cityid forKey:kSelectID];
    //存储用户的城市、商户bduss等
    
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    self.userCityName = loginInfo.cityname;
    self.selectedCityID = loginInfo.cityid;
    self.selectedCityName = loginInfo.cityname;
    self.bduss = loginInfo.memberbduss;
    self.shopBduss = loginInfo.shopbduss;
    self.shopID = loginInfo.shopid;
    self.shopName = loginInfo.shopname;
    self.nickName = loginInfo.username;
    self.hasLogin = YES;
}


- (void) cleanLoginInfo
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAccountBDUSS];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAccountName];
    [[NSUserDefaults standardUserDefaults]synchronize];
    self.bduss = nil;
    self.nickName = nil;
    self.hasLogin = NO;
}


-(void)saveUserEmailName:(NSString *)emailName{
    [[NSUserDefaults standardUserDefaults] setObject:emailName forKey:kAccountUserName];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    self.userEmailName = emailName;
}

-(void)getUserEmailName{
    NSString *emailName = [[NSUserDefaults standardUserDefaults] objectForKey:kAccountUserName];
    if (emailName != nil) {
        self.userEmailName = emailName;
    }
}

- (void) cleanServerLoginInfo
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAccountBDUSS];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAccountName];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAccountShopBDUSS];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kAccountShopID];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSelectName];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSelectID];
    
    [[NSUserDefaults standardUserDefaults]synchronize];
    self.bduss = nil;
    self.shopBduss = nil;
    self.shopID = nil;
    self.shopName = nil;
    self.nickName = nil;
    self.hasLogin = NO;
    self.hasLogin = NO;
}


//假如保存上次的城市名和城市id



- (void) setSelectedCityID:(NSString *)selectedCityID
{
    if (selectedCityID == nil) {
        self.selectedCityName = self.userCityName;
        self.userSelectStreetName = self.userCityStreetName;
        [[IManager sharedInstance] requestCityID:self.selectedCityName withDelegate:self];
    }else{
        [selectedCityID retain];
        [_selectedCityID release];
        _selectedCityID = selectedCityID;
        if ([self.selectedCityName isEqualToString:self.userCityName]) {
            self.userSelectStreetName = self.userCityStreetName;
        }else{
            self.userSelectStreetName = nil;
        }
        [[NSUserDefaults standardUserDefaults] setObject:self.selectedCityName forKey:kSelectName];
        [[NSUserDefaults standardUserDefaults] setObject:self.selectedCityID forKey:kSelectID];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
        UINavigationController *naviController = [RCAppDelegate.tabBarController.viewControllers objectAtIndex:2 withDefaultValue:nil];
        RCSearchMoreTagsVC *discountViewController = [[naviController viewControllers] objectAtIndex:0 withDefaultValue:nil];
        if ([discountViewController isKindOfClass:[RCSearchMoreTagsVC class]]) {
            discountViewController.cityID = selectedCityID;
            [discountViewController refreshData];
        }
      
        
        
    }
}

-(RCSearchCityListItem *)getSavedSelectCityInfo{
    NSString *selectid =  [[NSUserDefaults standardUserDefaults] objectForKey:kSelectID];
    NSString *selectname = [[NSUserDefaults standardUserDefaults] objectForKey:kSelectName];
    RCSearchCityListItem *item = [[RCSearchCityListItem alloc]init];
    
    if (selectid == nil || selectname == nil) {
        selectname = @"泰安";
        selectid = @"269";
    }
    self.selectedCityName = selectname;
    self.selectedCityID = selectid;
    
    item.cityID = selectid;
    item.cityName = selectname;
    return [item autorelease];
}


- (void) updateViewForError:(NSError *)errorInfo withRequestId:(int64_t)requestId
{
    
}

- (void) updateViewForSuccess:(IDataModel *)dataModel withRequestId:(int64_t)requestId
{
    RCSearchCityIDDataModel *data = (RCSearchCityIDDataModel*) dataModel;
    if (data.cityID != nil) {
        [[GloableEngineService sharedInstance] setSelectedCityID:data.cityID];

    }else{
        [[GloableEngineService sharedInstance] setSelectedCityID:@"0"];

    }
}


- (BOOL) alertLoginViewIfUnlogin:(UIViewController *)viewController
{
    if (!self.hasLogin) {
        RCLoginPageVC *vc = [[RCLoginPageVC alloc] initWithTmpLogin];
        if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0) {
            [vc setNeedsStatusBarAppearanceUpdate];
        }
        
        UINavigationController *rootNav = [[[UINavigationController alloc] initWithRootViewController:vc] autorelease];
        [viewController presentModalViewController:rootNav animated:YES];
        [vc release];
        return NO;
    }else{
        return YES;
    }
}
@end
